package com.edu.controller;

import com.edu.bean.User;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @SessionAttributes("msg"),
 * 只要该类下的任何一个方法，向Model中 存入了一个key是msg的对象，那么就会向session中存入一份一样的。
 */
@SessionAttributes({"loginUser","msg"})
@Controller
public class SessionController {

    /**
     * Controller中 向Session作用域 存取数据的方式1
     *  直接使用 HttpSession对象， 在方法中直接添加一个 HttpSession即可
     */
   /* @RequestMapping("/login1")
    public String login1(User user, HttpSession session){
        System.out.println("登录的用户是"+user);
        session.setAttribute("loginUser",user);
        return "redirect:success.jsp";
    }*/

    /**
     * 方式2  给Controller 添加一个 HttpSession属性
     */

//    @Resource
//    private HttpSession session;

//    @RequestMapping("/login1")
//    public String login1(User user){
//        System.out.println("登录的用户是"+user);
//        session.setAttribute("loginUser",user);
//        return "redirect:success.jsp";
//    }

    @RequestMapping("/login1")
    public String login2(User user ,Model model){
        model.addAttribute("msg","hello world");
        model.addAttribute("loginUser",user);
        return "redirect:success.jsp";
    }

    @RequestMapping("/getFromSession")
    public String getFromSession(Model model){
        System.out.println(model.getAttribute("loginUser"));
        System.out.println(model.getAttribute("msg"));
        return "redirect:index.jsp";
    }

    @RequestMapping("/getFromSession2")
    public String getFromSession2(@SessionAttribute(value = "loginUser",required = false) User user, @SessionAttribute(value = "msg",required = false) String msg){
        System.out.println(user);
        System.out.println(msg);
        return "redirect:index.jsp";
    }

}
